<template>
  <div>
    <myTips>
      <div slot="title">
        <i class="el-icon-warning"></i>
        温馨提示
      </div>
      <div slot="content">
        <div>
          1、人员信息需要从
          <router-link to="/department-user-info">人员管理</router-link>中去导出，修改excel表格中的相关数据后，通过此页面导入数据,实现批量修改人员信息
        </div>
        <div>2、excel表格中的表头请勿修改，人员编号/卡号/姓名这些列数据请勿修改，否则会导致修改信息失败</div>
        <!-- <div>3、当前只可批量修改人员的部门信息</div> -->
      </div>
    </myTips>
    <div class="unit_parameter">
      <div class="grid-content bg-purple aa">
        <div class="header_select">
          <!-- <div>
            <el-button type="primary" @click="thetemplate()" size="mini">execl模板下载</el-button>
          </div>-->
          <div class="bulk_import">
            <el-upload
              class="upload-demo"
              action
              :on-change="handleChange"
              :on-exceed="handleExceed"
              :on-remove="handleRemove"
              :file-list="fileListUpload"
              :limit="limitUpload"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              :auto-upload="false"
            >
              <el-button type="primary" @click="handleclickto()" size="mini">浏览文件</el-button>
            </el-upload>
          </div>
          <div class="packge_batch">
            <el-button type="primary" @click="packgebatchto(tableChecked)" size="mini">导入数据</el-button>
          </div>
        </div>
        <el-table
          :data="changestudentlist"
          :stripe="true"
          style="width: 100%"
          border="border"
          :header-cell-style="headFirst"
          highlight-current-row
          @selection-change="handleSelectionChange"
          :show-overflow-tooltip="true"
          key="table1"
          v-loading="importLoad"
          ref="importTable"
          :cell-style="(res) => headFirst_col(res, [])"
        >
          <!-- <el-table-column label="选择" width="55">
                                    <template slot-scope="scope">
                                        <el-checkbox :checked="scope.row.isKey== 1"/>
                                    </template>
          </el-table-column>-->
          <!-- <el-table-column align="center" type="selection" width="55"></el-table-column> -->
          <el-table-column label="是否选中" prop="isCheck" align="center" width="45">
            <template slot="header" slot-scope="scope">
              <el-checkbox :value="isSelectAll" @change="CheckSelectAll" :disabled="isError" />
            </template>
            <template slot-scope="scope">
              <el-checkbox
                :value="scope.row.isCheck"
                @change="(isCheck) => CheckSelect(isCheck, scope.row)"
                :disabled="isError"
              />
            </template>
          </el-table-column>
          <el-table-column label="错误原因" prop="errorStr" v-if="isError"></el-table-column>
          <el-table-column label="编号" prop="userNumber"></el-table-column>
          <el-table-column label="姓名" prop="userName"></el-table-column>
          <!-- <el-table-column label="卡号" prop="cardNumber"></el-table-column> -->
          <el-table-column label="部门" prop="departmentName"></el-table-column>
          <el-table-column label="身份/分组" prop="groupName"></el-table-column>
          <el-table-column label="入住房间" prop="roomName"></el-table-column>
          <el-table-column label="性别" prop="userSex"></el-table-column>
          <!-- <el-table-column label="生日" prop="birthday" min-width="140px"></el-table-column> -->
          <el-table-column label="手机号" prop="phoneNumber" min-width="100px"></el-table-column>
          <el-table-column label="联系人" prop="contact"></el-table-column>
          <el-table-column label="联系电话" prop="contactPhone"></el-table-column>
          <el-table-column label="身份证" prop="idCard" min-width="160px"></el-table-column>
          <!-- <el-table-column label="家庭地址" prop="homeAddress"></el-table-column>
          <el-table-column label="邮政编码" prop="postCode"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="预存款金额（元）" prop="advanceBalance" min-width="110px"></el-table-column>-->
        </el-table>
      </div>
    </div>
    <div class="page">
      <el-pagination
        @size-change="handleSizeChangeY"
        @current-change="handleCurrentChangepageY"
        :current-page="pageY"
        :page-sizes="[20, 40, 80, 120]"
        :page-size="pageSizeY"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalY"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
export default {
  data() {
    return {
      // 上传文件相关
      fileListUpload: [],
      limitUpload: 1,
      // 是否全选
      isSelectAll: false,
      // 表格中拿出的原始数据
      changestudentY: [],
      // 原始页数
      pageY: 1,
      // 每条个数
      pageSizeY: 20,
      // 总条数
      totalY: 0,
      // 导入的表格
      importLoad: false,
      // 是否显示错误原因
      isError: false,
      // 数据
      changestudentlist: [],
      // 选中数据
      tableChecked: []
    }
  },
  created() {
    this.changeschoolid = this.$store.state.user.changeschoolid
  },
  methods: {
    /**
     * 用户导入数据处理
     */
    initList() {
      // 关闭加载
      this.importLoad = false
      // 渲染表格初始化
      this.changestudentlist = []
      // 表格中拿出的原始数据
      this.changestudentY = []
      // 原始页数
      this.pageY = 1
      // 每条个数
      this.pageSizeY = 20
      // 总条数
      this.totalY = 0
      // 原始的显示数据数
      this.showPageSizeY = 20
      this.isSelectAll = false
    },

    // 用户导入显示,
    showImportDialog() {
      // 数据初始化
      this.initList()
      this.getunitconfiguration()
      this.importDialog = true
    },
    // 导入数据处理
    getData() {
      let arr = []
      this.changestudentY.map(item => {
        if (item.isCheck) {
          arr.push(item)
        }
      })
      return arr
    },
    //导入
    packgebatchto() {
      if (this.importLoad) {
        this.$message({
          showClose: true,
          message: '正在批量导入请勿重复操作',
          type: 'warning',
          duration: '500'
        })
        return false
      }
      let tableCheckedto = this.getData()
      if (tableCheckedto[0] && tableCheckedto[0].errorStr) {
        this.$message({
          message: '数据非法',
          type: 'warning'
        })
        return
      }
      let timeOut = Math.ceil(tableCheckedto.length / 1000)
      console.log(timeOut)
      // 批量加载条
      this.loading = Loading.service({
        lock: true,
        text: '正在批量修改中,请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      let encryptor = new JSEncrypt()
      encryptor.setPublicKey(this.publicKey)
      for (var i = 0; i < tableCheckedto.length; i++) {
        tableCheckedto[i].unitGuid = this.changeschoolid
        if (tableCheckedto[i].userSex == '男') {
          tableCheckedto[i].userSex = 0
        }
        if (tableCheckedto[i].userSex == '女') {
          tableCheckedto[i].userSex = 1
        }
        if (tableCheckedto[i].cardNumber) {
          tableCheckedto[i].cardNumber = tableCheckedto[i].cardNumber.toString()

          tableCheckedto[i].loginPassword = encryptor.encrypt(
            this.$md5(tableCheckedto[i].cardNumber)
          )
          tableCheckedto[i].loginName = tableCheckedto[i].cardNumber.toString()
        } else {
          tableCheckedto[i].cardNumber = tableCheckedto[i].cardNumber
        }
        tableCheckedto[i].unitGuid = this.changeschoolid
      }
      if (tableCheckedto.length == 0) {
        this.$message({
          message: '请选择需要修改信息的人员',
          type: 'warning'
        })
        return false
      }
      this.importLoad = true
      // console.log(tableCheckedto);
      this.$httpblob({
        url: this.$httpblob.adornUrl('/department/excel-user-update'),
        method: 'post',
        data: this.$httpblob.adornData({
          messageContent: tableCheckedto,
          messageType: 0
        })
      }).then(({ data }) => {
        // 关闭加载条
        this.loading.close()
        // 数据初始化
        this.initList()
        // console.log(data)
        if (data.messageCode == 500) {
          this.$message({
            message: data.errorMessage,
            type: 'warning'
          })
        }
        if (data.messageCode == 200) {
          this.table1 = false
          this.tablelist = data.messageContent
          if (data.messageContent.length != 0) {
            this.isError = true
            this.$message({
              showClose: true,
              duration: 1000 * 5,
              message: data.errorMessage,
              type: 'warning'
            })

            let arrto = data.messageContent
            arrto.map((item, index) => {
              item.isCheck = this.isSelectAll
              item.id = index
              item.userSex = item.userSex ? '女' : '男'
            })
            this.changestudentY = arrto
            this.getUserList(this.pageY, this.pageSizeY)
            this.totalY = arrto.length
            this.$nextTick(() => {
              this.$refs['importTable'].doLayout()
            })
          } else {
            this.isError = false
            this.$message({
              showClose: true,
              duration: 1000 * 5,
              message: data.errorMessage,
              type: 'success'
            })
            this.importDialog = false
            this.changestudentlist = []
            // this.initpage()
          }
        }
      })
    },
    //导入表格选择变更
    handleSelectionChange(val) {
      this.tableChecked = val
    },
    handleclickto() {},
    //导入函数
    importfxx(obj) {
      // 把错误号去除
      this.isError = false
      // 数据初始化
      this.initList()
      let _this = this
      // 通过DOM取文件数据
      this.file = obj
      var rABS = false //是否将文件读取为二进制字符串
      var f = this.file
      var reader = new FileReader()
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = ''
        var rABS = false //是否将文件读取为二进制字符串
        var pt = this
        var wb //读取完成的数据
        var outdata
        var reader = new FileReader()
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          var XLSX = require('xlsx')
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: 'base64'
            })
          } else {
            wb = XLSX.read(binary, {
              type: 'binary'
            })
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) //outdata就是你想要的东西
          this.da = [...outdata]
          let arr = []
          this.da.map(v => {
            let obj = {}
            obj.userName = v['姓名']
            obj.userNumber = v['人员编号']
            obj.cardNumber = v['卡号']
            obj.departmentName = v['部门']
            obj.departmentGuid = v['部门']
            obj.roomName = v['入住房间']
            obj.roomGuid = v['入住房间']
            obj.userSex = v['性别']
            obj.birthday = v['生日']
            obj.idCard = v['身份证']
            obj.phoneNumber = v['手机号']
            obj.contact = v['联系人']
            obj.contactPhone = v['联系人电话']
            obj.homeAddress = v['家庭住址']
            obj.postCode = v['邮政编码']
            obj.email = v['邮箱']
            obj.groupName = v['身份/分组']
            obj.advanceBalance = v['预存款金额（元）']
            arr.push(obj)
          })
          _this.studentlist = [...arr]
          let arrto = JSON.parse(JSON.stringify(_this.studentlist))
          console.log(arrto)
          // _this.studentlist = arrto
          if (arrto.length > 0) {
            for (var i = 0; i < arrto.length; i++) {
              if (arrto[i].birthday == undefined) {
                arrto[i].birthday = ''
              } else {
                arrto[i].birthday = _this.getdata(arrto[i].birthday)
              }
              arrto[i].unitGuid = this.changeschoolid
            }
          }
          console.log(arrto)

          // _this.changestudentlist = arrto;
          let list = []
          let is = 0
          let indexId = 0
          arrto.map((item, index) => {
            if (!item.userNumber) {
              delete arrto[index]
              is++
            } else {
              item.isCheck = _this.isSelectAll
              item.id = indexId
              indexId++
              list.push(item)
            }
          })
          if (is) {
            _this.$message({
              message: `已预览${list.length}条数据，忽略了${is}条未填写必填字段的数据`,
              type: 'warning'
            })
          }
          _this.changestudentY = list
          _this.getUserList(_this.pageY, _this.pageSizeY)
          _this.totalY = list.length
          // console.log(_this.changestudentlist);
          // console.log(_this.changestudentY);
        }
        reader.readAsArrayBuffer(f)
      }

      if (rABS) {
        reader.readAsArrayBuffer(f)
      } else {
        reader.readAsBinaryString(f)
      }
    },
    //导入excel相关
    handleRemove(file, fileList) {
      // 初始化
      this.initList()
      this.isError = false
      this.changestudentlist = []
      this.fileTemp = null
    },
    //导入excel相关
    handleExceed(file, fileList) {
      fileList[0].name = file[0].name
      this.fileTemps = file[0]
      if (this.fileTemps) {
        if (
          this.fileTemps.type ==
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          this.fileTemps.type == 'application/vnd.ms-excel'
        ) {
          this.changestudentlist = []
          this.table1 = true
          this.importfxx(this.fileTemps)
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    //导入excel相关
    handleChange(file, fileList) {
      this.fileTemp = file.raw
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
          this.fileTemp.type == 'application/vnd.ms-excel'
        ) {
          this.changestudentlist = []
          this.table1 = true
          this.importfxx(this.fileTemp)
        } else {
          this.$message({
            type: 'warning',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    //时间转换
    getdata(date) {
      date = Math.round(date * 100000) / 100000
      var Minustime = 1.33333 * 24 * 3600000
      date = new Date(date * 24 * 3600000 - Minustime)
      date.setYear(date.getFullYear() - 70)
      return this.dateFormat('YYYY-mm-dd', date)
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      // console.log(opt)
      for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    },

    // 用户导入分页
    handleSizeChangeY(val) {
      this.pageSizeY = val
      this.getUserList(this.pageY, this.pageSizeY)
    },
    handleCurrentChangepageY(val) {
      this.pageY = val
      this.getUserList(this.pageY, this.pageSizeY)
    },
    // 获取到用户数据，页面渲染
    getUserList(pagenum, pagesize) {
      this.changestudentlist = this.changestudentY.slice(
        (pagenum - 1) * pagesize,
        pagenum * pagesize
      )
    },

    // 选中数据
    CheckSelect(val, row) {
      // 因为是用索引当做id的。
      this.changestudentY[row.id].isCheck = val
      console.log(this.changestudentY)
    },
    // 全选按钮
    CheckSelectAll(val) {
      this.isSelectAll = val
      this.changestudentY.map(item => {
        item.isCheck = val
      })
    }, // 数据初始化
    /**
     * 用户导入数据处理
     */ initList() {
      // 关闭加载
      this.importLoad = false
      // 渲染表格初始化
      this.changestudentlist = []
      // 表格中拿出的原始数据
      this.changestudentY = []
      // 原始页数
      this.pageY = 1
      // 每条个数
      this.pageSizeY = 20
      // 总条数
      this.totalY = 0
      // 原始的显示数据数
      this.showPageSizeY = 20
      this.isSelectAll = false
    },
    // 用户导入分页
    handleSizeChangeY(val) {
      this.pageSizeY = val
      this.getUserList(this.pageY, this.pageSizeY)
    },
    handleCurrentChangepageY(val) {
      this.pageY = val
      this.getUserList(this.pageY, this.pageSizeY)
    },
    // 获取到用户数据，页面渲染
    getUserList(pagenum, pagesize) {
      this.changestudentlist = this.changestudentY.slice(
        (pagenum - 1) * pagesize,
        pagenum * pagesize
      )
    },

    // 选中数据
    CheckSelect(val, row) {
      // 因为是用索引当做id的。
      this.changestudentY[row.id].isCheck = val
      console.log(this.changestudentY)
    },
    // 全选按钮
    CheckSelectAll(val) {
      this.isSelectAll = val
      this.changestudentY.map(item => {
        item.isCheck = val
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.unit_parameter {
  padding: 0 10px;
}
a {
  text-decoration: underline;
}
.bg-purple {
  height: 100%;
  .header_title {
    padding: 10px 0 20px 0;
    font-weight: bolder;
    text-align: center;
    border-bottom: 1px solid #e5e9f2;
    color: #909399;
  }
  .el-table th {
    height: 100%;
    display: table-cell !important;
  }
  .page {
    padding-bottom: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .header_select {
    height: 35px;
    // background-color: #F5F5F5;
    width: 98%;

    display: flex;
    align-items: center;
    .cardnumber,
    .username,
    .usernumber {
      display: flex;
      align-items: center;
      padding-left: 10px;
      width: 200px;
      div:nth-child(1) {
        width: 40px;
      }
    }
    .searchbutton {
      // height:36px;
      padding-left: 10px;
      display: flex;
      flex: 1;
      justify-content: space-between;
      .addstudent {
        padding-right: 20px;
      }
      .el-checkbox {
        // align-self: left;
        width: 150px;
        margin-top: 20px;
      }
    }
    .bulk_import {
      //   padding-left: 20px;
      .upload-demo {
        display: flex;
        align-items: center;
        /deep/.el-upload-list__item-name {
          margin-right: 22px;
        }
      }
    }
    .packge_batch {
      padding-left: 20px;
    }
  }
}
.page {
  padding-bottom: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>